<template>
  <div class="distribution-plan">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>配货计划管理</h2>
        <p class="page-description">管理配货路线、车辆调度和配送时间安排</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新建配货计划
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="计划编号">
          <el-input v-model="searchForm.planCode" placeholder="请输入计划编号" clearable />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="配送区域">
          <el-select v-model="searchForm.area" placeholder="请选择区域" clearable>
            <el-option label="市区" value="urban" />
            <el-option label="郊区" value="suburban" />
            <el-option label="外地" value="remote" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planCode" label="计划编号" width="120" fixed="left" />
        <el-table-column prop="planName" label="计划名称" width="150" />
        <el-table-column prop="deliveryDate" label="配送日期" width="120" />
        <el-table-column prop="area" label="配送区域" width="100">
          <template #default="{ row }">
            <el-tag :type="getAreaTagType(row.area)">{{ getAreaText(row.area) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleCount" label="车辆数量" width="100" />
        <el-table-column prop="orderCount" label="订单数量" width="100" />
        <el-table-column prop="totalWeight" label="总重量(kg)" width="120" />
        <el-table-column prop="totalVolume" label="总体积(m³)" width="120" />
        <el-table-column prop="estimatedTime" label="预计时长" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :status="row.progress === 100 ? 'success' : ''" />
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editPlan(row)" :disabled="row.status === 'completed'">编辑</el-button>
            <el-button size="small" type="success" @click="executePlan(row)" :disabled="row.status !== 'pending'">执行</el-button>
            <el-button size="small" type="danger" @click="deletePlan(row)" :disabled="row.status === 'executing'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑配货计划对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingPlan ? '编辑配货计划' : '新建配货计划'"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="planFormRef"
        :model="planForm"
        :rules="planFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送日期" prop="deliveryDate">
              <el-date-picker
                v-model="planForm.deliveryDate"
                type="date"
                placeholder="选择配送日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送区域" prop="area">
              <el-select v-model="planForm.area" placeholder="请选择配送区域" style="width: 100%">
                <el-option label="市区" value="urban" />
                <el-option label="郊区" value="suburban" />
                <el-option label="外地" value="remote" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="planForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="高" value="high" />
                <el-option label="中" value="medium" />
                <el-option label="低" value="low" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="配送路线" prop="routes">
          <el-input
            v-model="planForm.routes"
            type="textarea"
            :rows="3"
            placeholder="请输入配送路线详情"
          />
        </el-form-item>
        <el-form-item label="车辆安排" prop="vehicles">
          <el-select
            v-model="planForm.vehicles"
            multiple
            placeholder="请选择配送车辆"
            style="width: 100%"
          >
            <el-option label="京A12345 - 大型货车" value="vehicle1" />
            <el-option label="京B67890 - 中型货车" value="vehicle2" />
            <el-option label="京C11111 - 小型货车" value="vehicle3" />
            <el-option label="京D22222 - 冷链车" value="vehicle4" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="planForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="savePlan" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 配货计划详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="配货计划详情" width="900px">
      <div v-if="currentPlan" class="plan-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="计划编号">{{ currentPlan.planCode }}</el-descriptions-item>
          <el-descriptions-item label="计划名称">{{ currentPlan.planName }}</el-descriptions-item>
          <el-descriptions-item label="配送日期">{{ currentPlan.deliveryDate }}</el-descriptions-item>
          <el-descriptions-item label="配送区域">
            <el-tag :type="getAreaTagType(currentPlan.area)">{{ getAreaText(currentPlan.area) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentPlan.status)">{{ getStatusText(currentPlan.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            <el-progress :percentage="currentPlan.progress" :status="currentPlan.progress === 100 ? 'success' : ''" />
          </el-descriptions-item>
          <el-descriptions-item label="车辆数量">{{ currentPlan.vehicleCount }}</el-descriptions-item>
          <el-descriptions-item label="订单数量">{{ currentPlan.orderCount }}</el-descriptions-item>
          <el-descriptions-item label="总重量">{{ currentPlan.totalWeight }} kg</el-descriptions-item>
          <el-descriptions-item label="总体积">{{ currentPlan.totalVolume }} m³</el-descriptions-item>
          <el-descriptions-item label="预计时长">{{ currentPlan.estimatedTime }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentPlan.creator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ currentPlan.createTime }}</el-descriptions-item>
          <el-descriptions-item label="配送路线" :span="2">{{ currentPlan.routes }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentPlan.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const editingPlan = ref(null)
const currentPlan = ref(null)
const selectedPlans = ref([])
const planFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  planCode: '',
  status: '',
  dateRange: [],
  area: ''
})

// 配货计划表单
const planForm = reactive({
  planName: '',
  deliveryDate: '',
  area: '',
  priority: 'medium',
  routes: '',
  vehicles: [],
  remark: ''
})

// 表单验证规则
const planFormRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  deliveryDate: [{ required: true, message: '请选择配送日期', trigger: 'change' }],
  area: [{ required: true, message: '请选择配送区域', trigger: 'change' }],
  routes: [{ required: true, message: '请输入配送路线', trigger: 'blur' }],
  vehicles: [{ required: true, message: '请选择配送车辆', trigger: 'change' }]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    planCode: 'DP202401001',
    planName: '市区配送计划A',
    deliveryDate: '2024-01-15',
    area: 'urban',
    vehicleCount: 3,
    orderCount: 25,
    totalWeight: 1250.5,
    totalVolume: 15.8,
    estimatedTime: '6小时',
    status: 'executing',
    progress: 65,
    creator: '张三',
    createTime: '2024-01-14 09:30:00',
    routes: '仓库 → 朝阳区 → 海淀区 → 西城区 → 东城区',
    remark: '优先配送生鲜商品'
  },
  {
    id: 2,
    planCode: 'DP202401002',
    planName: '郊区配送计划B',
    deliveryDate: '2024-01-16',
    area: 'suburban',
    vehicleCount: 2,
    orderCount: 18,
    totalWeight: 980.2,
    totalVolume: 12.3,
    estimatedTime: '8小时',
    status: 'pending',
    progress: 0,
    creator: '李四',
    createTime: '2024-01-14 10:15:00',
    routes: '仓库 → 昌平区 → 顺义区 → 通州区',
    remark: '注意交通管制时间'
  },
  {
    id: 3,
    planCode: 'DP202401003',
    planName: '外地配送计划C',
    deliveryDate: '2024-01-17',
    area: 'remote',
    vehicleCount: 1,
    orderCount: 8,
    totalWeight: 450.8,
    totalVolume: 8.5,
    estimatedTime: '12小时',
    status: 'completed',
    progress: 100,
    creator: '王五',
    createTime: '2024-01-13 14:20:00',
    routes: '仓库 → 天津 → 石家庄',
    remark: '长途配送，需要中途休息'
  }
]

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  loadData()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    planCode: '',
    status: '',
    dateRange: [],
    area: ''
  })
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedPlans.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const viewDetail = (plan) => {
  currentPlan.value = plan
  showDetailDialog.value = true
}

const editPlan = (plan) => {
  editingPlan.value = plan
  Object.assign(planForm, {
    planName: plan.planName,
    deliveryDate: plan.deliveryDate,
    area: plan.area,
    priority: 'medium',
    routes: plan.routes,
    vehicles: ['vehicle1', 'vehicle2'],
    remark: plan.remark
  })
  showCreateDialog.value = true
}

const executePlan = async (plan) => {
  try {
    await ElMessageBox.confirm('确认执行此配货计划？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    plan.status = 'executing'
    plan.progress = 10
    ElMessage.success('配货计划已开始执行')
  } catch {
    // 用户取消
  }
}

const deletePlan = async (plan) => {
  try {
    await ElMessageBox.confirm('确认删除此配货计划？删除后无法恢复。', '警告', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === plan.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消
  }
}

const savePlan = async () => {
  if (!planFormRef.value) return
  
  try {
    await planFormRef.value.validate()
    saving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (editingPlan.value) {
      // 编辑模式
      Object.assign(editingPlan.value, planForm)
      ElMessage.success('配货计划更新成功')
    } else {
      // 新建模式
      const newPlan = {
        id: Date.now(),
        planCode: `DP${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(tableData.value.length + 1).padStart(3, '0')}`,
        ...planForm,
        vehicleCount: planForm.vehicles.length,
        orderCount: Math.floor(Math.random() * 30) + 10,
        totalWeight: (Math.random() * 1000 + 500).toFixed(1),
        totalVolume: (Math.random() * 20 + 5).toFixed(1),
        estimatedTime: `${Math.floor(Math.random() * 8) + 4}小时`,
        status: 'pending',
        progress: 0,
        creator: '当前用户',
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newPlan)
      pagination.total++
      ElMessage.success('配货计划创建成功')
    }
    
    showCreateDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  Object.assign(planForm, {
    planName: '',
    deliveryDate: '',
    area: '',
    priority: 'medium',
    routes: '',
    vehicles: [],
    remark: ''
  })
  editingPlan.value = null
  if (planFormRef.value) {
    planFormRef.value.clearValidate()
  }
}

const handleDialogClose = () => {
  resetForm()
  showCreateDialog.value = false
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中')
}

// 辅助方法
const getStatusText = (status) => {
  const statusMap = {
    pending: '待执行',
    executing: '执行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    executing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || ''
}

const getAreaText = (area) => {
  const areaMap = {
    urban: '市区',
    suburban: '郊区',
    remote: '外地'
  }
  return areaMap[area] || area
}

const getAreaTagType = (area) => {
  const typeMap = {
    urban: 'success',
    suburban: 'warning',
    remote: 'danger'
  }
  return typeMap[area] || ''
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.distribution-plan {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.plan-detail {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .distribution-plan {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-right {
    width: 100%;
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>